﻿//DavidLee 2019/12/15
//TinyMCE plugin for netcorecms
//根据项目需要定制tinymce插件，用于将插入tinymce中的图片设置为轮播图
(function (domGlobals) {
    'use strict';
    // 获取插件管理对象
    //tinymce plugin example :https://codesandbox.io/embed/tinymce-dialog-openurl-demo-fpfew
    var global$1 = tinymce.util.Tools.resolve('tinymce.PluginManager');
    global$1.add('mycarousel', function (editor, url) {
        var openDialog = function (imgList) {
            $(editor.getBody()).find('img').each(function (i) {
                var $_ = $(this);
                var img = new Object();
                img.id = $_.attr('id');
                img.src = $_.attr('src');
                img.alt = $_.attr('alt');
                imgList.push(img);
            });

            function savecarouselImgs(imgList) {
                window.sessionStorage.setItem('tinymce.mycarousel', JSON.stringify(imgList));
            }

            return editor.windowManager.openUrl({
                title: 'Image Carousel',
                url: url + '/mycarousel.html',
                width: 800,
                height: 600,
                onMessage: function (instance, trigger) {
                    var carouselImgs = null;
                    if (trigger.mceAction === "geteditorimgs")
                        instance.sendMessage({
                            mceAction: 'editorimgs',
                            data: { mycarousel: imgList }
                        });
                    else if (trigger.mceAction === "deleteeditorimgs") {
                        //选中编辑器中图片设置为轮播图片，并删除编辑器中对应图片
                        carouselImgs = trigger.data.mycarousel;
                        savecarouselImgs(carouselImgs);
                        var $editor = $(editor.getBody());
                        $.each(carouselImgs, function (i, imgdata) {
                            var $imgElm = $editor.find("img[src='" + imgdata.src + "']");
                            if (typeof $imgElm !== "undefined")
                                $imgElm.remove();
                        });
                    }
                    else if (trigger.mceAction === "nodeleteeditorimgs") {
                        //选中编辑器中图片设置为轮播图片，但不删除编辑器中对应图片
                        carouselImgs = trigger.data.mycarousel;
                        savecarouselImgs(carouselImgs);
                    }
                }
            });
        };
        // Add a button that opens a window
        editor.ui.registry.addButton('mycarousel', {
            text: 'mycarousel',
            onAction: () => {
                var imgList = new Array();
                openDialog(imgList);
            }
        });

        return {
            getMetadata: function () {
                return {
                    name: "myCarousel",
                    url: "http://exampleplugindocsurl.com"
                };
            }
        };
    });

}(window));
